const { successData } = require('../utils/common')
const {
  createAddrError,
  updateAddrError,
  findAllAddrError,
  serverError,
} = require('../constant/error.type')

const {
  createAddr,
  findAllAddr,
  updateAddr,
  findOneAddr,
  removeAddr,
  setDefaultAddr,
} = require('../service/addr.service')

class AddrController {
  async create(ctx) {
    const { id: user_id } = ctx.state.user
    const { consignee, phone, address } = ctx.request.body
    try {
      const res = await createAddr({ user_id, consignee, phone, address })
      ctx.body = res ? successData('添加地址成功', res) : createAddrError
    } catch (error) {
      console.error('添加地址失败', error)
      ctx.app.emit('error', createAddrError, ctx)
    }
  }

  async findAll(ctx) {
    const { id: user_id } = ctx.state.user

    try {
      const res = await findAllAddr(user_id)
      ctx.body = res ? successData('获取地址列表成功', res) : findAllAddrError
    } catch (error) {
      console.error('获取地址列表失败', error)
      return ctx.app.emit('error', findAllAddrError, ctx)
    }
  }

  async findOne(ctx, next) {
    const { id } = ctx.request.params
    updateAddrError.message = '要修改的地址信息不存在'
    try {
      const res = await findOneAddr(id)
      if (res) {
        await next()
      } else {
        return ctx.app.emit('error', updateAddrError, ctx)
      }
    } catch (error) {
      console.error('要修改的地址信息不存在', error)
      return ctx.app.emit('error', updateAddrError, ctx)
    }
  }

  async update(ctx) {
    const { id } = ctx.request.params
    // const { id: user_id } = ctx.state.user
    // const { consignee, phone, address } = ctx.request.body
    try {
      const res = await updateAddr(id, ctx.request.body)
      ctx.body = res ? successData('修改地址成功', res) : updateAddrError
    } catch (error) {
      console.error('修改地址失败', error)
      ctx.app.emit('error', updateAddrError, ctx)
    }
  }

  async remove(ctx) {
    const { id } = ctx.request.params
    serverError.message = '删除地址失败'
    try {
      const res = await removeAddr(id)
      ctx.body = res ? successData('删除地址成功', res) : serverError
    } catch (error) {
      console.error(serverError.message, error)
      ctx.app.emit('error', serverError, ctx)
    }
  }

  async setDefault(ctx) {
    const { id } = ctx.request.params
    const { id: user_id } = ctx.state.user
    serverError.message = '设置默认地址失败'
    // console.log(id, user_id)
    try {
      const res = await setDefaultAddr(id, user_id)
      ctx.body = res ? successData('设置默认地址成功', res) : serverError
    } catch (error) {
      console.error(serverError.message, error)
      ctx.app.emit('error', serverError, ctx)
    }
  }
}

module.exports = new AddrController()
